package com.dhcc.sdc.cdss.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.dhcc.cdc.busi.entity.CdcDictionaryEntity;
import com.dhcc.cdc.sys.cache.config.CdcConfigCache;
import com.dhcc.cdc.sys.service.IConfigurationService;
import com.dhcc.cdc.sys.service.IDictionaryService;
import com.dhcc.core.framework.util.CommonUtil;
import com.dhcc.core.framework.util.RedisUtil;
import com.dhcc.sdc.base.dao.SdcQcCdssLinkMapper;
import com.dhcc.sdc.base.entity.SdcQcCdssLinkEntity;
import com.dhcc.sdc.busi.dao.SdcQcMapper;
import com.dhcc.sdc.busi.dao.SdcShowPremiseMapper;
import com.dhcc.sdc.busi.entity.SdcQcEntity;
import com.dhcc.sdc.busi.entity.SdcShowPremiseEntity;
import com.dhcc.sdc.busi.function.GetSdcValueSrv;
import com.dhcc.sdc.cdss.dao.*;
import com.dhcc.sdc.cdss.dto.*;
import com.dhcc.sdc.cdss.entity.*;
import com.dhcc.sdc.cdss.service.*;
import com.dhcc.sds.base.cache.qcentity.QcEntityCache;
import com.dhcc.sds.base.entity.SdsQcentityEntity;
import com.dhcc.sds.standard.dao.SdsStandSourceFieldMapper;
import com.dhcc.sds.standard.dao.SdsStandSourceMapper;
import com.dhcc.sds.standard.entity.SdsStandSourceEntity;
import com.dhcc.sds.standard.entity.SdsStandSourceFieldEntity;
import com.dhcc.sds.standard.function.GetRuleValueSrv;
import com.dhcc.sds.standard.service.IsdsStandRuleCalService;
import com.dhcc.sds.util.DateUtil;
import com.googlecode.aviator.AviatorEvaluator;
import org.apache.commons.jexl2.Expression;
import org.apache.commons.jexl2.JexlContext;
import org.apache.commons.jexl2.JexlEngine;
import org.apache.commons.jexl2.MapContext;
import org.apache.http.HttpEntity;
import org.apache.http.client.CookieStore;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.cookie.Cookie;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service("cdssApiService")
public class CdssApiServiceImpl implements ICdssApiService {
    @Autowired
    private IConfigurationService configurationService;
    @Autowired
    private CdssApiMapper cdssApiMapper;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private SdcCdssItemResultMapper sdcCdssItemResultMapper;
    @Autowired
    private SdcQcMapper sdcQcMapper;
    @Autowired
    private IDictionaryService dictionaryService;
    @Autowired
    private SdcCdssItemMapper sdcCdssItemMapper;
    @Autowired
    private SdsStandSourceMapper sdsStandSourceMapper;
    @Autowired
    private SdsStandSourceFieldMapper sdsStandSourceFieldMapper;
    @Autowired
    private SdcShowPremiseMapper sdcShowPremiseMapper;
    @Autowired
    private SdcQcCdssLinkMapper sdcQcCdssLinkMapper;
    @Autowired
    private ISdcCdssItemService sdcCdssItemService;
    @Autowired
    private ISdcCdssItemLogService sdcCdssItemLogService;
    @Autowired
    private IsdsStandRuleCalService isdsStandRuleCalService;

    //小括号及其里面内容
    private static String p1 = "\\(.*?\\)";

    @Override
    public ArgumentData createArgumentData(String episodeId) {
        ArgumentData argumentData = new ArgumentData();
        // 基本信息
        PatientInfo patientInfo = cdssApiMapper.patientInfo(episodeId);
        // 诊断信息
        List<DiagnosisInfo> diagnosisInfos = cdssApiMapper.diagnosisInfos(episodeId);
        // 医嘱信息
        List<OrderInfo> orderInfos = cdssApiMapper.orderInfos(episodeId);
        // 入院记录信息
        ProgressNote progressNote = cdssApiMapper.progressNote(episodeId);
        // 检查信息
        List<ExamInfo> examInfos = cdssApiMapper.examInfos(episodeId);
        // 检验信息
        List<LabInfo> labInfos = cdssApiMapper.labInfos(episodeId);
        // 生命体征
        SignInfo signInfo = cdssApiMapper.signInfo(episodeId);
        // 过敏原信息
//        List<AllergyInfo> allergyInfos = cdssApiMapper.allergyInfos(episodeId);
        // 输血信息
//        List<BloodTransInfo> bloodTransInfos = cdssApiMapper.bloodTransInfos(episodeId);
        // 评估信息
        List<RatingScaleInfo> ratingScaleInfos = cdssApiMapper.ratingScoreInfos(episodeId);
        // 手术信息
        List<OperationReportInfo> operationReportInfos = cdssApiMapper.operationReportInfos(episodeId);

        if (CommonUtil.isNotEmpty(patientInfo)) {
            argumentData.setPatientInfo(patientInfo);
        }
        if (CommonUtil.isNotEmpty(diagnosisInfos)) {
            argumentData.setDiagnosisList(diagnosisInfos);
        }
        if (CommonUtil.isNotEmpty(orderInfos)) {
            argumentData.setOrderEntry(orderInfos);
        }
        if (CommonUtil.isNotEmpty(progressNote)) {
            argumentData.setProgressNoteList(progressNote);
        }
        if (CommonUtil.isNotEmpty(examInfos)) {
            argumentData.setExamList(examInfos);
        }
        if (CommonUtil.isNotEmpty(labInfos)) {
            argumentData.setLabList(labInfos);
        }
        if (CommonUtil.isNotEmpty(signInfo)) {
            argumentData.setSigns(signInfo);
        }
//        if (CommonUtil.isNotEmpty(allergyInfos)) {
//            argumentData.setAllergyList(allergyInfos);
//        }
//        if (CommonUtil.isNotEmpty(bloodTransInfos)) {
//            argumentData.setBloodTransInfo(bloodTransInfos);
//        }
        if (CommonUtil.isNotEmpty(ratingScaleInfos)) {
            argumentData.setRatingScaleInfo(ratingScaleInfos);
        }
        if(CommonUtil.isNotEmpty(operationReportInfos)){
            argumentData.setOperationReportInfo(operationReportInfos);
        }
        return argumentData;
    }

    @Override
    public JSONObject cdssData(ArgumentData argumentData) {
        //CDSS服务地址
        String cdssServerUrl = CdcConfigCache.me().getValueByKey("SDS", "CDSSServer");
        // 创建httpClient对象
        CloseableHttpClient client = HttpClients.createDefault();
        // 调用execute,返回response
        CloseableHttpResponse response = null;
        JSONObject cdssInfo = new JSONObject();
        JSONArray result = new JSONArray();
        try {
            if (!redisUtil.hasKey("cdss_token")) {
                this.GetCdssToken();
            }
            String tokenStr = redisUtil.get("cdss_token");
            // 创建cdss接口请求实例
            String url = cdssServerUrl + "/api/recommend";
            HttpPost post = new HttpPost(url);
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(3000).setConnectTimeout(2000).build();//设置请求和传输超时时间
            post.setConfig(requestConfig);
            post.setHeader("Content-Type", "application/json;charset=utf8");
            post.setHeader("Access_token", tokenStr); // 请求携带token
            // 参数
            // 该次解析关闭循环引用检测
            String params = JSON.toJSONString(argumentData, SerializerFeature.DisableCircularReferenceDetect);
            params = clearSpecialChar(params);
            StringEntity strEntity = new StringEntity(params, "UTF-8");
            post.setEntity(strEntity);
            response = client.execute(post);
            String str = EntityUtils.toString(response.getEntity());
            result = JSONArray.parseObject(str).getJSONArray("Result");
        } catch (Exception e) {
            e.printStackTrace();
            // 绑定sdc中自定义项目（cdss中无条件不能返回的项目） python 可以返回了，修改为绑定单病种自定义项目
            result = bindSdcItem(argumentData.getType(), argumentData.getGroupInfo().getSingleDiseaseId(), result);
            cdssInfo.put("cdssStatus", "error");
            cdssInfo.put("cdssInfo", result);
            return cdssInfo;
        } finally {
            try {
                if (client != null) {
                    client.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        // 绑定sdc中自定义项目（cdss中无条件不能返回的项目）  python 可以返回了，修改为绑定单病种自定义项目
        result = bindSdcItem(argumentData.getType(), argumentData.getGroupInfo().getSingleDiseaseId(), result);
        cdssInfo.put("cdssStatus", "success");
        cdssInfo.put("cdssInfo", result);
        return cdssInfo;
    }

    private JSONArray bindSdcItem(String type, String entityId, JSONArray cdssResult) {
        JSONArray bindResult = new JSONArray();
        JSONObject interObj = new JSONObject();
        // cdss请求异常的情况
        if (cdssResult == null || cdssResult.size() == 0) {
            cdssResult = new JSONArray();
            String[] subTypeArr = type.split(",");
            for (String subType : subTypeArr) {
                interObj = new JSONObject();
                interObj.put("InterfaceName", ArgumentData.ParamType.getEnumByType(subType).getName());
                interObj.put("InterfaceValue", new JSONArray());
                cdssResult.add(interObj);
            }
        }
        for (int m = 0; m < cdssResult.size(); m++) {
            interObj = cdssResult.getJSONObject(m);
            String interfaceName = interObj.getString("InterfaceName");
            JSONArray interfaceValue = interObj.getJSONArray("InterfaceValue");
            Map params = new HashMap();
            params.put("qcentityId", entityId);
            //python 可以返回了，修改为绑定单病种自定义项目
//            params.put("noCondition", 1);
            String redisKey = entityId + "_";
            if (CommonUtil.equals("推荐检验检查", interfaceName)) {
                redisKey = redisKey + "RecomLabExam";
                // 自定义检查项目
                List<Map<String, Object>> examItems = new ArrayList<>();
                if (redisUtil.hasKey(redisKey + "_" + "exam")) {
                    //取出List
                    examItems = JSON.parseObject(redisUtil.get(redisKey + "_" + "exam"), new TypeReference<List<Map<String, Object>>>() {
                    });
                } else {
                    params.put("itemType", 2); //检查项目
                    examItems = sdcCdssItemMapper.sdcItemList(params);
                    redisUtil.set(redisKey + "_" + "exam", examItems, 6 * 60 * 60);
                }
                interfaceValue.addAll(JSONArray.parseArray(JSON.toJSONString(examItems)));
                // 自定义检验项目
                List<Map<String, Object>> labItems = new ArrayList<>();
                if (redisUtil.hasKey(redisKey + "_" + "lab")) {
                    //取出List
                    labItems = JSON.parseObject(redisUtil.get(redisKey + "_" + "lab"), new TypeReference<List<Map<String, Object>>>() {
                    });
                } else {
                    params.put("itemType", 3); // 检验项目
                    labItems = sdcCdssItemMapper.sdcItemList(params);
                    redisUtil.set(redisKey + "_" + "lab", labItems, 6 * 60 * 60);
                }
                interfaceValue.addAll(JSONArray.parseArray(JSON.toJSONString(labItems)));
            } else if (CommonUtil.equals("推荐治疗方案", interfaceName)) {
                redisKey = redisKey + "AssistTreat";
                // 自定义医嘱项目
                List<Map<String, Object>> treatItems = new ArrayList<>();
                if (redisUtil.hasKey(redisKey)) {
                    //取出List
                    treatItems = JSON.parseObject(redisUtil.get(redisKey), new TypeReference<List<Map<String, Object>>>() {
                    });
                } else {
                    params.put("itemType", 4); // 治疗项目
                    treatItems = sdcCdssItemMapper.sdcItemList(params);
                    redisUtil.set(redisKey, treatItems, 6 * 60 * 60);
                }
                // 医嘱子项
                /*for (int i = 0, l = treatItems.size(); i < l; i++) {
                    Map<String, Object> map = treatItems.get(i);
                    Map chilMap = new HashMap();
                    chilMap.put("itemId", map.get("ItemID"));
                    List<Map<String, Object>> childrenList = sdcCdssTreachildrenMapper.childrenList(chilMap);
                    map.put("children", JSONArray.parseArray(JSON.toJSONString(childrenList)));
                    treatItems.set(i, map);
                }*/
                interfaceValue.addAll(JSONArray.parseArray(JSON.toJSONString(treatItems)));
            } else if (CommonUtil.equals("推荐护理处置", interfaceName)) {
                redisKey = redisKey + "RecomNursing";
                // 自定义护理项目
                List<Map<String, Object>> nursingItems = new ArrayList<>();
                if (redisUtil.hasKey(redisKey)) {
                    //取出List
                    nursingItems = JSON.parseObject(redisUtil.get(redisKey), new TypeReference<List<Map<String, Object>>>() {
                    });
                } else {
                    params.put("itemType", 5); // 护理项目
                    nursingItems = sdcCdssItemMapper.sdcItemList(params);
                    redisUtil.set(redisKey, nursingItems, 6 * 60 * 60);
                }
                interfaceValue.addAll(JSONArray.parseArray(JSON.toJSONString(nursingItems)));
            } else if (CommonUtil.equals("推荐评估量表", interfaceName)) {
                redisKey = redisKey + "RecomAssess";
                // 自定义评估项目
                List<Map<String, Object>> evalItems = new ArrayList<>();
                if (redisUtil.hasKey(redisKey)) {
                    //取出List
                    evalItems = JSON.parseObject(redisUtil.get(redisKey), new TypeReference<List<Map<String, Object>>>() {
                    });
                } else {
                    params.put("itemType", 1); // 评估项目
                    evalItems = sdcCdssItemMapper.sdcItemList(params);
                    redisUtil.set(redisKey, evalItems, 6 * 60 * 60);
                }
                interfaceValue.addAll(JSONArray.parseArray(JSON.toJSONString(evalItems)));
            }
            interObj.put("InterfaceValue", interfaceValue);
            bindResult.add(interObj);
        }
        return bindResult;
    }

    @Override
    public JSONArray filterResult(String episodeId, Long entityId, JSONArray cdssInfo) {
        String vteQcModule = CdcConfigCache.me().getValueByKey("SDS", "VTEQcModule");
        JSONArray filterResult = new JSONArray();
        Map param = new HashMap<>();
        param.put("episodeId", episodeId);
        param.put("entityId", entityId);
        for (Object obj : cdssInfo) {
            JSONObject interObj = JSONObject.parseObject(obj.toString());
            String interfaceName = interObj.getString("InterfaceName");
            JSONArray interfaceValue = JSONArray.parseArray(interObj.getString("InterfaceValue"));

            if ("推荐评估量表".equals(interfaceName)) {
                for (int i = interfaceValue.size() - 1; i >= 0; i--) {
                    JSONObject item = JSONObject.parseObject(interfaceValue.get(i).toString());
                    String nodeId = item.getString("NodeId");
                    if(CommonUtil.isEmpty(nodeId)){
                        nodeId = item.getString("nodeId");
                    }
                    String itemId = item.getString("ItemID");
                    if(CommonUtil.isEmpty(itemId)){
                        itemId = item.getString("itemId");
                    }
                    param.put("nodeId", nodeId);
                    param.put("itemId", itemId);
                    param.put("result", 1);
                    item.put("ItemDone", 0);

                    // 获取详细信息
                    SdcCdssItemEntity evalEntity = new SdcCdssItemEntity();
                    evalEntity.setNodeId(nodeId);
                    evalEntity.setItemId(itemId);
                    if(CommonUtil.isEmpty(nodeId)){
                        System.out.println("异常");
                    }
                    evalEntity = sdcCdssItemMapper.selectOne(evalEntity);
                    if (evalEntity != null) {
                        // 如果系统配置不进行VTE相关项目的质控，且该项目是VTE通用方案则跳过
                        if (CommonUtil.notEquals(vteQcModule, "Y") && Objects.equals(evalEntity.getType(), 1)) {
                            interfaceValue.remove(i);
                            continue;
                        }
                        // 诊疗推荐项目完成情况判断
                        Map itemMap = BeanUtil.beanToMap(evalEntity);
                        Integer result = 1;
                        try {
                            result = this.judgeItem(Long.valueOf(episodeId), interfaceName, itemMap);
                        } catch (Exception e) {
                            e.printStackTrace();
                            result = 1;
                        }
                        if (result != 0) {//如果判断结果是已完成 或 判断结果是不确定
                            interfaceValue.remove(i);
                            continue;
                        }
                    }
                    // 获取关联质控项目信息
                    List<SdcQcCdssLinkEntity> links = sdcQcCdssLinkMapper.selectList(new EntityWrapper<SdcQcCdssLinkEntity>().eq("cdss_node_id", nodeId).eq("type", 1));
                    if (!links.isEmpty()) {
                        SdcQcCdssLinkEntity link = links.get(0);
                        SdcQcEntity qcEntity = sdcQcMapper.selectById(link.getQcItemId());
                        if(CommonUtil.isNotEmpty(qcEntity)) {
                            item.put("QCID", qcEntity.getId());
                            item.put("QCDesc", qcEntity.getQcDesc());
                        }
                    }
                    // 最新评估信息
                    Map evalInfo = cdssApiMapper.evalInfo(param);
                    if (CommonUtil.isNotEmpty(evalInfo)) {
                        item.put("ItemDone", 1);
                        item.putAll(evalInfo);
                    }
                    Map contraindicationInfo = cdssApiMapper.contraindicationInfo(param);
                    if (CommonUtil.isNotEmpty(contraindicationInfo)){
                        item.putAll(contraindicationInfo);
                    }

                    interfaceValue.set(i, item);
                }
                interObj.put("InterfaceValue", interfaceValue);
            } else if ("推荐检验检查".equals(interfaceName)) {
                String examItemStr = "";
                String labItemStr = "";
                for (int i = interfaceValue.size() - 1; i >= 0; i--) {
                    JSONObject item = JSONObject.parseObject(interfaceValue.get(i).toString());
                    String nodeId = item.getString("NodeId");
                    if(CommonUtil.isEmpty(nodeId)){
                        nodeId = item.getString("nodeId");
                    }
                    String itemId = item.getString("ItemID");
                    if(CommonUtil.isEmpty(itemId)){
                        itemId = item.getString("itemId");
                    }
                    param.put("nodeId", nodeId);
                    param.put("itemId", itemId);
                    param.put("result", 1);
                    String itemType = item.getString("ItemType");
                    Long qcId = item.getLong("QCID");
                    List<SdcCdssItemResultEntity> itemResultEntityList = sdcCdssItemResultMapper.list(param);
                    if (itemResultEntityList.size() > 0) {
                        // 当前项目已完成
                        interfaceValue.remove(i);
                        continue;
                    } else {
                        // 当前项目未记录
                        Integer result = 1;
                        if ("122".equals(itemType)) {
                            // 获取详细信息
                            SdcCdssItemEntity examEntity = new SdcCdssItemEntity();
                            examEntity.setNodeId(nodeId);
                            examEntity.setItemId(itemId);
                            examEntity = sdcCdssItemMapper.selectOne(examEntity);
                            if (examEntity != null) {
                                // 如果系统配置不进行VTE相关项目的质控，且该项目是VTE通用方案则跳过
                                if (CommonUtil.notEquals(vteQcModule, "Y") && Objects.equals(examEntity.getType(), 1)) {
                                    interfaceValue.remove(i);
                                    continue;
                                }
                                // 诊疗推荐项目完成情况判断
                                Map itemMap = BeanUtil.beanToMap(examEntity);
                                try {
                                    result = this.judgeItem(Long.valueOf(episodeId), interfaceName, itemMap);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    result = 1;
                                }
                            }
                            if (result == 0) {
                                // 获取关联质控项目信息
                                List<SdcQcCdssLinkEntity> links = sdcQcCdssLinkMapper.selectList(new EntityWrapper<SdcQcCdssLinkEntity>().eq("cdss_node_id", nodeId).eq("type", 2));
                                if (!links.isEmpty()) {
                                    SdcQcCdssLinkEntity link = links.get(0);
                                    qcId = link.getQcItemId();
                                }
                                examItemStr = itemId + "," + examItemStr;
                            }
                        } else {
                            // 获取详细信息
                            SdcCdssItemEntity labEntity = new SdcCdssItemEntity();
                            labEntity.setNodeId(nodeId);
                            labEntity.setItemId(itemId);
                            labEntity = sdcCdssItemMapper.selectOne(labEntity);
                            if (labEntity != null) {
                                // 如果系统配置不进行VTE相关项目的质控，且该项目是VTE通用方案则跳过
                                if (CommonUtil.notEquals(vteQcModule, "Y") && Objects.equals(labEntity.getType(), 1)) {
                                    interfaceValue.remove(i);
                                    continue;
                                }
                                // 诊疗推荐项目完成情况判断
                                Map itemMap = BeanUtil.beanToMap(labEntity);
                                try {
                                    result = this.judgeItem(Long.valueOf(episodeId), interfaceName, itemMap);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    result = 1;
                                }
                            }
                            if (result == 0) {
                                // 获取关联质控项目信息
                                List<SdcQcCdssLinkEntity> links = sdcQcCdssLinkMapper.selectList(new EntityWrapper<SdcQcCdssLinkEntity>().eq("cdss_node_id", nodeId).eq("type", 3));
                                if (!links.isEmpty()) {
                                    SdcQcCdssLinkEntity link = links.get(0);
                                    qcId = link.getQcItemId();
                                }
                                labItemStr = itemId + "," + labItemStr;
                            }
                        }
                        if (result == 1) {
                            interfaceValue.remove(i);
                            SdcCdssItemResultEntity sdcCdssItemResult = new SdcCdssItemResultEntity();
                            sdcCdssItemResult.setEpisodeId(Long.valueOf(episodeId));
                            sdcCdssItemResult.setNodeId(nodeId);
                            sdcCdssItemResult.setResult(1);
                            sdcCdssItemResult.insert();
                            continue;
                        } else if (result == -1) {
                            interfaceValue.remove(i);
                            continue;
                        }
                    }
                    Map contraindicationInfo = cdssApiMapper.contraindicationInfo(param);
                    if (CommonUtil.isNotEmpty(contraindicationInfo)){
                        item.putAll(contraindicationInfo);
                        interfaceValue.set(i, item);
                    }
                    if (qcId != null) {
                        SdcQcEntity qcEntity = sdcQcMapper.selectById(qcId);
                        item.put("QCID", qcId);
                        item.put("QCDesc", qcEntity.getQcDesc());
                        interfaceValue.set(i, item);
                    }
                }
                interObj.put("InterfaceExamItemStr", examItemStr);
                interObj.put("InterfaceLabItemStr", labItemStr);
                interObj.put("InterfaceValue", interfaceValue);
            } else if ("推荐治疗方案".equals(interfaceName)) {
                String itemStr = "";
                for (int i = interfaceValue.size() - 1; i >= 0; i--) {
                    JSONObject item = JSONObject.parseObject(interfaceValue.get(i).toString());
                    String nodeId = item.getString("NodeId");
                    if(CommonUtil.isEmpty(nodeId)){
                        nodeId = item.getString("nodeId");
                    }
                    String itemId = item.getString("ItemID");
                    if(CommonUtil.isEmpty(itemId)){
                        itemId = item.getString("itemId");
                    }
                    param.put("nodeId", nodeId);
                    param.put("itemId", itemId);
                    param.put("result", 1);
                    Long qcId = item.getLong("QCID");
                    List<SdcCdssItemResultEntity> itemResultEntityList = sdcCdssItemResultMapper.list(param);
                    if (itemResultEntityList.size() > 0) {
                        // 当前项目已完成
                        interfaceValue.remove(i);
                        continue;
                    } else {
                        // 获取详细信息
                        SdcCdssItemEntity treatEntity = new SdcCdssItemEntity();
                        treatEntity.setNodeId(nodeId);
                        treatEntity.setItemId(itemId);
                        treatEntity = sdcCdssItemMapper.selectOne(treatEntity);
                        Integer result = 1;
                        if (treatEntity != null) {
                            // 如果系统配置不进行VTE相关项目的质控，且该项目是VTE通用方案则跳过
                            if (CommonUtil.notEquals(vteQcModule, "Y") && Objects.equals(treatEntity.getType(), 1)) {
                                interfaceValue.remove(i);
                                continue;
                            }
                            // 诊疗推荐项目完成情况判断
                            Map itemMap = BeanUtil.beanToMap(treatEntity);
                            try {
                                result = this.judgeItem(Long.valueOf(episodeId), interfaceName, itemMap);
                            } catch (Exception e) {
                                e.printStackTrace();
                                result = 1;
                            }
                        }
                        if (result == 1) {
                            interfaceValue.remove(i);
                            SdcCdssItemResultEntity sdcCdssItemResult = new SdcCdssItemResultEntity();
                            sdcCdssItemResult.setEpisodeId(Long.valueOf(episodeId));
                            sdcCdssItemResult.setNodeId(nodeId);
                            sdcCdssItemResult.setResult(1);
                            sdcCdssItemResult.insert();
                            continue;
                        } else if (result == -1) {
                            interfaceValue.remove(i);
                            continue;
                        } else {
                            // 获取关联质控项目信息
                            List<SdcQcCdssLinkEntity> links = sdcQcCdssLinkMapper.selectList(new EntityWrapper<SdcQcCdssLinkEntity>().eq("cdss_node_id", nodeId).eq("type", 4));
                            if (!links.isEmpty()) {
                                SdcQcCdssLinkEntity link = links.get(0);
                                qcId = link.getQcItemId();
                            }
                            itemStr = itemId + "," + itemStr;
                        }
                    }
                    Map contraindicationInfo = cdssApiMapper.contraindicationInfo(param);
                    if (CommonUtil.isNotEmpty(contraindicationInfo)){
                        item.putAll(contraindicationInfo);
                        interfaceValue.set(i, item);
                    }
                    if (qcId != null) {
                        SdcQcEntity qcEntity = sdcQcMapper.selectById(qcId);
                        item.put("QCID", qcId);
                        item.put("QCDesc", qcEntity.getQcDesc());
                        interfaceValue.set(i, item);
                    }
                }
                interObj.put("InterfaceItemStr", itemStr);
                interObj.put("InterfaceValue", interfaceValue);
            } else if ("推荐护理处置".equals(interfaceName)) {
                String itemStr = "";
                for (int i = interfaceValue.size() - 1; i >= 0; i--) {
                    JSONObject item = JSONObject.parseObject(interfaceValue.get(i).toString());
                    String nodeId = item.getString("NodeId");
                    if(CommonUtil.isEmpty(nodeId)){
                        nodeId = item.getString("nodeId");
                    }
                    String itemId = item.getString("ItemID");
                    if(CommonUtil.isEmpty(itemId)){
                        itemId = item.getString("itemId");
                    }
                    param.put("nodeId", nodeId);
                    param.put("itemId", itemId);
                    param.put("result", 1);
                    Long qcId = item.getLong("QCID");
                    List<SdcCdssItemResultEntity> itemResultEntityList = sdcCdssItemResultMapper.list(param);
                    if (itemResultEntityList.size() > 0) {
                        // 当前项目已完成
                        interfaceValue.remove(i);
                        continue;
                    } else {
                        // 当前项目未记录
                        // 获取详细信息
                        SdcCdssItemEntity nursngEntity = new SdcCdssItemEntity();
                        nursngEntity.setNodeId(nodeId);
                        nursngEntity.setItemId(itemId);
                        nursngEntity = sdcCdssItemMapper.selectOne(nursngEntity);
                        Integer result = 1;
                        if (nursngEntity != null) {
                            // 如果系统配置不进行VTE相关项目的质控，且该项目是VTE通用方案则跳过
                            if (CommonUtil.notEquals(vteQcModule, "Y") && Objects.equals(nursngEntity.getType(), 1)) {
                                interfaceValue.remove(i);
                                continue;
                            }
                            // 诊疗推荐项目完成情况判断
                            Map itemMap = BeanUtil.beanToMap(nursngEntity);
                            try {
                                result = this.judgeItem(Long.valueOf(episodeId), interfaceName, itemMap);
                            } catch (Exception e) {
                                e.printStackTrace();
                                result = 1;
                            }
                        }
                        if (result == 1) {
                            interfaceValue.remove(i);
                            SdcCdssItemResultEntity sdcCdssItemResult = new SdcCdssItemResultEntity();
                            sdcCdssItemResult.setEpisodeId(Long.valueOf(episodeId));
                            sdcCdssItemResult.setNodeId(nodeId);
                            sdcCdssItemResult.setResult(1);
                            sdcCdssItemResult.insert();
                            continue;
                        } else if (result == -1) {
                            interfaceValue.remove(i);
                            continue;
                        } else {
                            // 获取关联质控项目信息
                            List<SdcQcCdssLinkEntity> links = sdcQcCdssLinkMapper.selectList(new EntityWrapper<SdcQcCdssLinkEntity>().eq("cdss_node_id", nodeId).eq("type", 5));
                            if (!links.isEmpty()) {
                                SdcQcCdssLinkEntity link = links.get(0);
                                qcId = link.getQcItemId();
                            }
                            itemStr = itemId + "," + itemStr;
                        }
                    }
                    Map contraindicationInfo = cdssApiMapper.contraindicationInfo(param);
                    if (CommonUtil.isNotEmpty(contraindicationInfo)){
                        item.putAll(contraindicationInfo);
                        interfaceValue.set(i, item);
                    }
                    if (qcId != null) {
                        SdcQcEntity qcEntity = sdcQcMapper.selectById(qcId);
                        item.put("QCID", qcId);
                        item.put("QCDesc", qcEntity.getQcDesc());
                        interfaceValue.set(i, item);
                    }
                }
                interObj.put("InterfaceItemStr", itemStr);
                interObj.put("InterfaceValue", interfaceValue);
            }
            filterResult.add(interObj);
        }
        return filterResult;
    }

    @Override
    public JSONArray filterForbiddenItem(String episodeId, Long entityId, JSONArray cdssInfo) {
        JSONArray filterForbiddenItem = new JSONArray();
        for (Object obj : cdssInfo){
            JSONObject interObj = JSONObject.parseObject(obj.toString());
            JSONArray interfaceValue = JSONArray.parseArray(interObj.getString("InterfaceValue"));
            for (int i = interfaceValue.size() - 1; i >= 0; i--) {
                JSONObject item = JSONObject.parseObject(interfaceValue.get(i).toString());
                String nodeId = item.getString("NodeId");
                String itemId = item.getString("ItemID");
                if(CommonUtil.isEmpty(nodeId)){
                    nodeId = item.getString("nodeId");
                }
                if(CommonUtil.isEmpty(itemId)){
                    itemId = item.getString("itemId");
                }
                item.put("ItemDone", 0);
                // 获取详细信息
                SdcCdssItemEntity evalEntity = new SdcCdssItemEntity();
                evalEntity.setNodeId(nodeId);
                evalEntity.setItemId(itemId);
                if(CommonUtil.isEmpty(nodeId)){
                    System.out.println("异常");
                }
                evalEntity = sdcCdssItemMapper.selectOne(evalEntity);
                if (evalEntity != null && evalEntity.getIsActive() != 1){
                    interfaceValue.remove(i);
                }
            }
            interObj.put("InterfaceValue", interfaceValue);
            filterForbiddenItem.add(interObj);
        }
        return filterForbiddenItem;
    }

    /**
     * 诊疗推荐项目完成情况判断
     *
     * @param episodeId
     * @param itemName
     * @param itemMap
     * @return -1: 待观察，下次继续；0：要推送；1：已完成的
     */
    public Integer judgeItem(Long episodeId, String itemName, Map<String, Object> itemMap) throws Exception {
        Integer result;
        String nodeId = String.valueOf(itemMap.get("nodeId"));
        String itemId = String.valueOf(itemMap.get("itemId"));
        String entityId = String.valueOf(itemMap.get("qcentityId"));
        Map param = new HashMap();
        param.put("episodeId", episodeId);
        param.put("nodeId", nodeId);
        param.put("itemId", itemId);
        // 无效医嘱
        List<Long> invalidOrderStatus = new ArrayList<>();
        if (redisUtil.hasKey("ORD_STAT_C")) {
            invalidOrderStatus.add(Long.valueOf(redisUtil.get("ORD_STAT_C")));
        } else {
            CdcDictionaryEntity cdcDictionaryEntity = dictionaryService.getMatchCtDic("SDS", "SDMatchCdcDic", "ORD_STAT_C");// 撤销-医嘱状态
            if (cdcDictionaryEntity != null) {
                redisUtil.set("ORD_STAT_C", cdcDictionaryEntity.getId());
                invalidOrderStatus.add(cdcDictionaryEntity.getId());
            }
        }
        if (redisUtil.hasKey("ORD_STAT_U")) {
            invalidOrderStatus.add(Long.valueOf(redisUtil.get("ORD_STAT_U")));
        } else {
            CdcDictionaryEntity cdcDictionaryEntity = dictionaryService.getMatchCtDic("SDS", "SDMatchCdcDic", "ORD_STAT_U");// 作废-医嘱状态
            if (cdcDictionaryEntity != null) {
                redisUtil.set("ORD_STAT_U", cdcDictionaryEntity.getId());
                invalidOrderStatus.add(cdcDictionaryEntity.getId());
            }
        }
        // 无效医嘱状态ID
        param.put("invalidOrderStatus", invalidOrderStatus);

        //显示时间段
        if(CommonUtil.isNotEmpty(itemMap.get("data"))){
            String sourceId = String.valueOf(itemMap.get("data"));
            int pushStart = Integer.valueOf(String.valueOf(itemMap.get("pushStart")));
            String timeUnit = String.valueOf(itemMap.get("timeUnit"));
            Date now = new Date();
            // 获取参照数据时间
            SdsStandSourceEntity source = sdsStandSourceMapper.selectById(sourceId);
            SdsStandSourceEntity parentSourceEntity = sdsStandSourceMapper.selectById(source.getParentId());
            String methodName = parentSourceEntity.getSourceCode();
            Class GetRuleValueSrv = Class.forName("com.dhcc.sds.standard.function.GetRuleValueSrv");
            com.dhcc.sds.standard.function.GetRuleValueSrv function = (GetRuleValueSrv) GetRuleValueSrv.newInstance();
            Method method1 = GetRuleValueSrv.getMethod(methodName, Long.class, Long.class, Integer.class, Long.class, Long.class,String.class);
            String referTime = "";
            referTime = String.valueOf(method1.invoke(function, episodeId, itemMap.get("data"), 0, itemMap.get("dic"), itemMap.get("getTiming"),null));
            if (CommonUtil.isEmpty(referTime)) {
                return -1;
            }
            // 时间-检索范围
            Date startDate = DateUtil.getDateByFilter(DateUtil.parseTime(referTime), pushStart, timeUnit);
            Date endDate = DateUtil.parseTime("2099-12-31 00:00:00");
            if (itemMap.get("pushEnd") != null) {
                int pushEnd = Integer.valueOf(String.valueOf(itemMap.get("pushEnd")));
                endDate = DateUtil.getDateByFilter(DateUtil.parseTime(referTime), pushEnd, timeUnit);
                // 判断参照结束时间与当前时间，如果参照结束时间早于当前时间，则当前项目视为过期项目，不再提示。
                if (endDate.before(now)) {
                    return 1;
                }
            }
            param.put("startDate", startDate);
            param.put("endDate", endDate);
        }

//        if (CommonUtil.isNotEmpty(itemMap.get("dataSource"))) {
//            String sourceId = String.valueOf(itemMap.get("dataSource"));
//            String fieldId = String.valueOf(itemMap.get("dataSourceItem"));
//            String paramStr = String.valueOf(itemMap.get("param"));
//            int pushStart = Integer.valueOf(String.valueOf(itemMap.get("pushStart")));
//            String timeUnit = String.valueOf(itemMap.get("timeUnit"));
//            Date now = new Date();
//            // 获取参照数据时间
//            SdsStandSourceEntity sourceEntity = sdsStandSourceMapper.selectById(sourceId);
//            String sourceCode = sourceEntity.getSourceCode();
//            String sourceFiled = "";
//            if (fieldId != null) {
//                SdsStandSourceFieldEntity sourceFieldEntity1 = sdsStandSourceFieldMapper.selectById(fieldId);
//                sourceFiled = sourceFieldEntity1.getFieldCode();
//            }
//            Class GetSdcValueSrv = Class.forName("com.dhcc.sdc.busi.function.GetSdcValueSrv");
//            com.dhcc.sdc.busi.function.GetSdcValueSrv function = (GetSdcValueSrv) GetSdcValueSrv.newInstance();
//            Method method1 = GetSdcValueSrv.getMethod(sourceCode, Long.class, String.class, String.class);
//            String referTime = String.valueOf(method1.invoke(function, episodeId, paramStr, sourceFiled));
//            if (CommonUtil.isEmpty(referTime)) {
//                return -1;
//            }
//            // 时间-检索范围
//            Date startDate = DateUtil.getDateByFilter(DateUtil.parseTime(referTime), pushStart, timeUnit);
//            Date endDate = DateUtil.parseTime("2099-12-31 00:00:00");
//            if (itemMap.get("pushEnd") != null) {
//                int pushEnd = Integer.valueOf(String.valueOf(itemMap.get("pushEnd")));
//                endDate = DateUtil.getDateByFilter(DateUtil.parseTime(referTime), pushEnd, timeUnit);
//                // 判断参照结束时间与当前时间，如果参照结束时间早于当前时间，则当前项目视为过期项目，不再提示。
//                if (endDate.before(now)) {
//                    return 1;
//                }
//            }
//            param.put("startDate", startDate);
//            param.put("endDate", endDate);
//        }

        // 显示前提结果结算
        boolean showPremiseResult = true;
        if (CommonUtil.isNotEmpty(itemMap.get("showPremise"))) {
            String showPremiseStr = itemMap.get("showPremise").toString();
//            showPremiseResult = isdsStandRuleCalService.handleRuleExpressions(showPremiseStr,episodeId);
            Map<String, Object> res = (Map) isdsStandRuleCalService.handleRuleExpressions(showPremiseStr, episodeId,null);
            showPremiseResult = (boolean) res.get("bool");
        }

        if ("推荐评估量表".equals(itemName)) {
            if (showPremiseResult) {
                result = 0;
            } else {
                result = 1;
            }
        } else {
            // 进行存在判断
            int cnt = cdssApiMapper.isOrder(param);
            if (cnt == 0 && showPremiseResult) {
                result = 0;
            } else {
                result = 1;
            }
        }
        return result;
    }

    /**
     * 返回值改造
     *
     * @param bfVal
     * @param ruleType
     * @return
     */
    private String modelRuleValue(String bfVal, String ruleType) {
        String afVal = "";
        if (CommonUtil.isEmpty(bfVal)) {
            return afVal;
        }
        long divisor = 1;
        switch (ruleType) {
            case "Day":
                // 一天毫秒数
                divisor = 24 * 60 * 60 * 1000;
                afVal = String.valueOf(com.dhcc.core.framework.util.DateUtil.parse(bfVal).getTime() / divisor);
                break;
            case "Hour":
                // 1小时毫秒数
                divisor = 60 * 60 * 1000;
                afVal = String.valueOf(com.dhcc.core.framework.util.DateUtil.parse(bfVal).getTime() / divisor);
                break;
            case "Minute":
                // 一分钟毫秒数
                divisor = 60 * 1000;
                afVal = String.valueOf(com.dhcc.core.framework.util.DateUtil.parse(bfVal).getTime() / divisor);
                break;
            case "String":
                afVal = "\"" + bfVal + "\"";
                break;
            default:
                afVal = bfVal;
                break;
        }
        return afVal;
    }

    @Override
    public Map<String, Object> updateEntityRecommendData(Long entityId) throws Exception {
        //CDSS服务地址
        String cdssServerUrl = CdcConfigCache.me().getValueByKey("SDS", "CDSSServer");
        // 创建httpClient对象
        CloseableHttpClient client = HttpClients.createDefault();
        String url = cdssServerUrl + "/api/get_all_result";
        //创建urlBuilder
        URIBuilder uriBuilder = new URIBuilder(url);
        //设置参数
        String entityName = "";
        if (!StringUtils.isEmpty(entityId)) {
            SdsQcentityEntity qcEntity = QcEntityCache.me().getQcEntityById(entityId);
            if(CommonUtil.isNotEmpty(qcEntity.getCdssName())){
                entityName=qcEntity.getCdssName();
            }else{
                entityName = qcEntity.getBtDesc();
            }

        }
        uriBuilder.setParameter("disease_name", entityName);
        // 创建请求方法的实例，并指定请求URL
        HttpGet get = new HttpGet(uriBuilder.build());
        // 参数
        // 全局关闭
        // JSON.DEFAULT_GENERATE_FEATURE |= SerializerFeature.DisableCircularReferenceDetect.getMask();
        // 该次解析关闭循环引用检测
        // 调用execute,返回response
        CloseableHttpResponse response = null;
        Map<String, Object> result = new HashMap<>();
        try {
            response = client.execute(get);
            HttpEntity httpEntity = response.getEntity();
            String str = EntityUtils.toString(httpEntity);
            String s = clearSpecialChar(str);
            JSONObject jsonObject = JSONArray.parseObject(s);

            for (String key : jsonObject.keySet()) {
                JSONObject jsonObject1 = jsonObject.getJSONObject(key);
                //根据key获取病种id
                Long qcEntityId = cdssApiMapper.selectQcentityIdByName(key);
                if (StringUtils.isEmpty(qcEntityId)) {
                    continue;
                }
                List<String> cdssNodeIds = sdcCdssItemService.handleJsonArrayData(jsonObject1, qcEntityId);
                //对比删除cdss去掉的方案
                deleteRepeatCdssData(qcEntityId, cdssNodeIds);

            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (client != null) {
                    client.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return result;
    }

    private String handleNodeIds(Long entityId, List<String> cdssNursingNodeIds, List<String> cdssLabNodeIds, List<String> cdssExamNodeIds, List<String> cdssTreatNodeIds, List<String> cdssEvalNodeIds) {
        String res = "";
        //护理
       /* List<String> nursingNodeIds = cdssNursingService.selectNodeIds(entityId);
        nursingNodeIds.removeAll(cdssNursingNodeIds);
        if (nursingNodeIds.size() > 0) {
            cdssNursingService.deleteByNodeIds(nursingNodeIds);
            res += "删除护理" + nursingNodeIds.size() + "条";
        }
        //检验
        List<String> labNodeIds = cdssLabService.selectNodeIds(entityId);
        labNodeIds.removeAll(cdssLabNodeIds);
        if (labNodeIds.size() > 0) {
            cdssLabService.deleteByNodeIds(labNodeIds);
            res += "删除检验" + labNodeIds.size() + "条";
        }
        //检查
        List<String> examNodeIds = cdssExamService.selectNodeIds(entityId);
        examNodeIds.removeAll(cdssExamNodeIds);
        if (examNodeIds.size() > 0) {
            cdssExamService.deleteByNodeIds(examNodeIds);
            res += "删除检查" + examNodeIds.size() + "条";
        }
        //治疗
        List<String> treatNodeIds = cdssTreatService.selectNodeIds(entityId);
        treatNodeIds.removeAll(cdssTreatNodeIds);
        if (treatNodeIds.size() > 0) {
            cdssTreatService.deleteByNodeIds(treatNodeIds);
            res += "删除治疗" + treatNodeIds.size() + "条";
        }
        //评估
        List<String> evalNodeIds = cdssEvalService.selectNodeIds(entityId);
        evalNodeIds.removeAll(cdssEvalNodeIds);
        if (evalNodeIds.size() > 0) {
            cdssEvalService.deleteByNodeIds(evalNodeIds);
            res += "删除评估" + evalNodeIds.size() + "条";
        }*/
        return res;
    }

    private void deleteRepeatCdssData(Long entityId, List<String> cdssNodeIds) {
        List<String> nodeIds = sdcCdssItemService.selectNodeIds(entityId);
        nodeIds.removeAll(cdssNodeIds);
        if (nodeIds.size() > 0) {
            sdcCdssItemLogService.deleteLog(nodeIds);
            sdcCdssItemService.deleteByNodeIds(nodeIds);
        }
    }

    /**
     * 获取CDSS的token信息，并加入缓存
     */
    private void GetCdssToken() {
        //CDSS服务地址
        String cdssServerUrl = CdcConfigCache.me().getValueByKey("SDS", "CDSSServer");
        // 创建httpClient对象
        CloseableHttpClient client = HttpClients.createDefault();

        // 调用execute,返回response
        CloseableHttpResponse response = null;
        try {
            // 构造post数据
            StringEntity loginEntity = new StringEntity("{\"username\":\"guest\",\"password\":\"tseug\"} ", "UTF-8");
            loginEntity.setContentType("application/json;charset=utf8");

            // 创建cdss登录请求
            String loginUrl = cdssServerUrl + "/api/login";
            HttpPost loginPost = new HttpPost(loginUrl);
            // 注入post数据
            loginPost.setEntity(loginEntity);
            response = client.execute(loginPost);
            String str = EntityUtils.toString(response.getEntity());
            String tokenStr = JSONObject.parseObject(str).getString("access_token");
            // 加入到redis缓存
            redisUtil.set("cdss_token", tokenStr);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (client != null) {
                    client.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public JSONArray getEntityMap() {
        List<SdsQcentityEntityDto> sdsQcentityEntities = this.cdssApiMapper.selectQcentityEntity();
        JSONArray officeArry = new JSONArray();
        JSONObject obj = new JSONObject();
        obj.put("value", "");
        obj.put("text", "全部");
        officeArry.add(obj);
        for (SdsQcentityEntityDto qcentityEntity : sdsQcentityEntities) {
            JSONObject officeObj = new JSONObject();
            officeObj.put("value", qcentityEntity.getId() + "");
            officeObj.put("text", qcentityEntity.getBtDesc());
            officeArry.add(officeObj);
        }
        return officeArry;
    }

    /**
     * 移除字符串中非法字符
     *
     * @param targetStr
     * @return
     */
    public static String clearSpecialChar(String targetStr) {
        if (CommonUtil.isNotEmpty(targetStr)) {
            targetStr = targetStr.replaceAll("[\t\n\r]", "");// 换行符、制表符、回车符
            targetStr = targetStr.replaceAll("◆", "");// 特殊符号
            targetStr = targetStr.replaceAll("\'", ""); // 半角单引号
            targetStr = targetStr.replaceAll("\\\\n", "");
        }
        return targetStr;
    }

    public static void cdssTest() {
        String name = "guest"; //
        String password = "tseug"; //

        // 全局请求设置
        RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build();
        // 创建cookie store的本地实例
        CookieStore cookieStore = new BasicCookieStore();
        // 创建HttpClient上下文
        HttpClientContext context = HttpClientContext.create();
        context.setCookieStore(cookieStore);

        // 创建一个HttpClient
        CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig)
                .setDefaultCookieStore(cookieStore).build();

        CloseableHttpResponse res = null;

        // 创建本地的HTTP内容
        try {
            try {
                // 构造post数据
                StringEntity strEntity = new StringEntity("{\"username\":\"guest\",\"password\":\"tseug\"} ", "UTF-8");
                strEntity.setContentType("application/json;charset=utf8");

                // 创建一个post请求
                HttpPost post = new HttpPost("http://192.144.152.252:8080/api/login");
                // 注入post数据
                post.setEntity(strEntity);
                res = httpClient.execute(post, context);

                // 打印响应信息，查看是否登陆是否成功
                System.out.println("打印响应信息===========");
                System.out.println(res.toString());
                res.close();

                System.out.println("登陆成功后,新的Cookie:===============");
                for (Cookie c : context.getCookieStore().getCookies()) {
                    System.out.println(c.getName() + ": " + c.getValue());
                }
            } finally {
                httpClient.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        cdssTest();
    }
}
